#include "../include/CServer.h"
#include <boost/beast.hpp>
#include "../include/asioContextPool.h"
#include <iostream>
#include "../include/tcp_connection.h"
CServer::CServer(boost::asio::io_context &_io_con,unsigned short port):_io_context(_io_con)
,_acceptor(_io_con,boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(),port))
{
}

void CServer::start_accept(){
    //延长声明周期，避免被错误释放了
    auto self=shared_from_this();

    //为什么一下这样不会造成调度过深呢？
    //由于调用async_accept这个函数，是将该事件的回调注册到io_context，该函数的行为也仅此而已,且生效一次，
    //一次事件执行完对应的回调，需要继续注册，才能继续后续事件的触发的回调调度
    boost::asio::io_context &io_context_item=asioContextPool::get_instance()->get_io_context();
    std::shared_ptr<tcp_connection>con(new tcp_connection(io_context_item));
    _acceptor.async_accept(con->get_socket(),[con,self](boost::beast::error_code ec){
        if(ec){ 
            //返回true,表明出错
            //self->start_accept();
            std::cout<<"尝试接收连接出错"<<std::endl;
            return;
        }
        //处理新连接，交给httpconnection去处理,并开启异步read
        std::cout<<"新来的一个连接,相关信息为："<<std::endl;
        std::cout<<con->get_socket().remote_endpoint().address()<<" "<<con->get_socket().remote_endpoint().port()<<std::endl;
        con->async_read_head();
        

        
        //继续接收连接
        self->start_accept();

    });
}